<template>
<Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
  <FormItem prop="userName">
    <Input v-model="form.userName" placeholder="请输入用户名">
    <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
    </Input>
  </FormItem>
  <FormItem prop="password">
    <Input type="password" v-model="form.password" placeholder="请输入密码">
    <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
    </Input>
  </FormItem>
  <FormItem>
    <Button type="primary" :loading="saveLoading" @click="handleSubmit">
        <span v-if="!saveLoading">登录</span>
        <span v-else>正在登录...</span>
     </Button>
  </FormItem>
</Form>
</template>
<script>
export default {
  name: 'LoginForm',
  props: {
    userNameRules: {
      type: Array,
      default: () => {
        return [{
          required: true,
          message: '账号不能为空',
          trigger: 'blur'
        }]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        return [{
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        }]
      }
    }
  },
  data() {
    return {
      form: {
        userName: 'dev@lucms.com',
        password: '123456'
      },
      saveLoading: false
    }
  },
  computed: {
    rules() {
      return {
        userName: this.userNameRules,
        password: this.passwordRules
      }
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          this.$emit('on-success-valid', {
            email: this.form.userName,
            password: this.form.password
          })
        } else {
          this.saveLoading = false
        }
      })
    }
  }
}
</script>
